﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.ExportToVis.CApExportToVisPLMXMLWriter
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using System.IO;
using System.Xml;
using Tecnomatix.Engineering;


namespace DnProcessSimulateCommands.ExportToVis;

public class CApExportToVisPLMXMLWriter
{
  private TxTransformation sourceTransformation;
  private TxTransformation targetTransformation;
  private string cadid;
  private ITxObject movingObj;
  public string m_animationFramesFileName;
  private string m_filename;
  private CApExportToVisViewModel _apVM;
  private string plmxmlFileExtension = ".plmxml";

  public CApExportToVisPLMXMLWriter(string filename, CApExportToVisViewModel _apVM)
  {
    this.m_filename = filename;
    this._apVM = _apVM;
  }

  public void CreateFile() => this.EditCadIds(new FileInfo(this.m_animationFramesFileName));

  private void EditCadIds(FileInfo file)
  {
    XmlDocument doc = new XmlDocument();
    doc.Load(file.FullName);
    this.GenerateCadIds(doc);
    this.ReplaceIDsForAttribute(doc, "MotionEntityRef", "MotionEntityRefID");
    this.ReplaceIDsForAttribute(doc, "Transform", "TransformID");
    doc.Save($"{this._apVM.Output}\\{this.m_filename}.plmxml");
  }

  private void GenerateCadIds(XmlDocument doc)
  {
    foreach (XmlNode xmlNode in doc.GetElementsByTagName("ApplicationRef"))
    {
      XmlAttribute attribute = xmlNode.Attributes["label"];
      if (attribute != null)
      {
        string objectId = attribute.Value;
        if (!string.IsNullOrEmpty(objectId))
        {
          CApExportToVisCadIdGenerator visCadIdGenerator = new CApExportToVisCadIdGenerator(objectId, this.m_filename);
          attribute.Value = $"#PLMXML(PS_API-doc/NGID('{visCadIdGenerator.GenerateCadIdFromObjectId()}\\0'))";
        }
      }
    }
  }

  private void ReplaceIDsForAttribute(XmlDocument doc, string node, string attribute)
  {
    int num = 0;
    string str = attribute;
    foreach (XmlNode xmlNode in doc.GetElementsByTagName(node))
    {
      XmlAttribute attribute1 = xmlNode.Attributes["id"];
      if (attribute1 != null && !string.IsNullOrEmpty(attribute1.Value))
      {
        attribute1.Value = $"{str}_{num.ToString()}";
        ++num;
      }
    }
  }
}
